package com.fortune.cat.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @author zhaozeyang
 * @date 2019/4/26 19:38
 * @description
 */
public class SignProcessorUtils {

    public static String encrypt(String privateKey, String data, String encryptName) {
        Mac mac;
        try {
            SecretKeySpec key = new SecretKeySpec(privateKey.getBytes(StandardCharsets.UTF_8), encryptName);
            mac = Mac.getInstance(encryptName);
            mac.init(key);
        } catch (Exception e) {
            throw new RuntimeException(encryptName + " error !", e);
        }
        byte[] bytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return toHexString(bytes).toUpperCase();
    }

    static String toHexString(byte[] bytes) {
        StringBuilder hash = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hash.append('0');
            }
            hash.append(hex);
        }
        return hash.toString();
    }
}
